package org.scirp.ijmis.util;

import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.spec.RSAPublicKeySpec;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Security {
	public static void main(String[] args) {
	}

	public static String TriDesEncrypt(String pKey, String pIV, String pContent) {
		String ret = "";
		try {
			IvParameterSpec iv = new IvParameterSpec(pIV.getBytes());
			SecretKeySpec key = new SecretKeySpec(pKey.getBytes(), "DESede");
			Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");

			cipher.init(1, key, iv);

			BASE64Encoder enc64 = new BASE64Encoder();

			ret = enc64.encodeBuffer(cipher.doFinal(pContent.getBytes("utf-8")));

			return ret.replaceAll("\r\n", "");
		} catch (Exception ex) {
		}
		return "";
	}

	public static String RSAEncrypt(String pKey, String pContent) {
		String ret = "";
		try {
			int startIndex = pKey.indexOf("<Modulus>") + 9;
			int endIndex = pKey.indexOf("</Modulus>");

			byte[] b = new BASE64Decoder().decodeBuffer(pKey.substring(startIndex, endIndex));

			String N = Bin2HexString(b);

			startIndex = pKey.indexOf("<Exponent>") + 10;
			endIndex = pKey.indexOf("</Exponent>");

			b = new BASE64Decoder().decodeBuffer(pKey.substring(startIndex, endIndex));

			String E = Bin2HexString(b);

			BigInteger bigN = new BigInteger(N, 16);
			BigInteger bigE = new BigInteger(E, 16);
			RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(bigN, bigE);
			Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

			cipher.init(1, KeyFactory.getInstance("RSA").generatePublic(pubSpec));

			BASE64Encoder enc64 = new BASE64Encoder();

			ret = enc64.encodeBuffer(cipher.doFinal(pContent.getBytes("utf-8")));

			return ret.replaceAll("\r\n", "");
		} catch (Exception ex) {
		}
		return "";
	}

	public static String Bin2HexString(byte[] pArray) {
		try {
			StringBuilder sb = new StringBuilder();

			for (int i = 0; i < pArray.length; ++i) {
				sb.append(Integer.toHexString(pArray[i] & 0xFF | 0x100).toLowerCase().substring(1, 3));
			}

			return sb.toString();
		} catch (Exception e) {
		}
		return "";
	}

	public static String MD5(String pContent) {
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");

			return Bin2HexString(md5.digest(pContent.getBytes("gb2312")));
		} catch (Exception e) {
		}
		return "";
	}
}
